﻿using LinqToExcel;
using SchoolCommunicationSystem.Models;
using SCS.Business;
using SCS.Common.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SchoolCommunicationSystem.Controllers
{
    public class TeacherController : Controller
    {
        private TeacherServices _teacherServices = new TeacherServices();

        private MembershipService _memberServices = new MembershipService();

        #region Table
        /// <summary>
        /// Get list of teacher
        /// </summary>
        /// <param name="page">1</param>
        /// <param name="searchString">string</param>
        /// <param name="sort">name</param>
        /// <param name="sortDir">ASC</param>
        /// <returns>View</returns>
        public ActionResult Table(int page = 1, string searchString = "", string sort = "name", string sortDir = "ASC")
        {
            const int pageSize = 1000;
            var totalRows = _teacherServices.CountTeacher(searchString);
            if (totalRows <= pageSize)
            {
                page = 1;
            }
            sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
            IEnumerable<Teacher> teacher = null;
            if (string.IsNullOrEmpty(searchString))
            {
                teacher = _teacherServices.GetTeacherPaging(page, pageSize);
            }
            else
            {
                teacher = _teacherServices.SearchTeacherPaging(page, pageSize, searchString);
            }
            var data = new TeacherListViewModels()
            {
                TotalRows = totalRows,
                PageSize = pageSize,
                Teachers = teacher
            };
            return View(data);
        }
        #endregion

        #region ViewParentInformation
        /// <summary>
        /// ViewParentInformation
        /// </summary>
        /// <param name="page">1</param>
        /// <param name="sortDir">ASC</param>
        /// <returns>View</returns>
        public ActionResult ViewParentInformation(int page = 1, string sortDir = "ASC")
        {
            TeacherViewModels teacherViewModel = new TeacherViewModels();

            string userName = User.Identity.Name;
            var teacher = _memberServices.GetUser(userName);
            int classID = teacher.Teachers.FirstOrDefault().Classes.FirstOrDefault().classID;
            string className = teacher.Teachers.FirstOrDefault().Classes.FirstOrDefault().ClassInSchoolYears.FirstOrDefault().className;
            //////////////////////////////////
            const int pageSize = 1000;
            var totalRows = _teacherServices.getLearnerList(classID).Count();
            if (totalRows <= pageSize)
            {
                page = 1;
            }
            sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
            var data = new TeacherViewModels()
            {
                learners = _teacherServices.getLearnerList(classID),
                className = className,
                TotalRows = totalRows,
                PageSize = pageSize
            };
            return View(data);
        }
        #endregion

        #region AddTeacher
        /// <summary>
        /// Pre add a teacher
        /// </summary>
        /// <returns>View</returns>
        public ActionResult AddTeacher()
        {
            var gender = new List<SelectListItem>();
            gender.Add(new SelectListItem() { Text = "Nam", Value = "M" });
            gender.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
            ViewBag.Genders = gender;
            return View();
        }

        /// <summary>
        /// Add a teacher
        /// </summary>
        /// <param name="teacher">teacher</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult AddTeacher(Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                teacher.deactived = false;
                _teacherServices.AddTeacher(teacher);
                string lastTeacher = teacher.teacherName;
                TempData["Msg"] = "Đã thêm " + lastTeacher + " vào danh sách giáo viên thành công";
                
                SCS.Business.MembershipService _membershipServices = new SCS.Business.MembershipService();
                string userName = User.Identity.Name;
                var user = _membershipServices.GetUser(userName);
                if (user != null)
                {
                    if (user.MembershipRoles.FirstOrDefault().roleID == 1)
                    {
                        return RedirectToAction("Table");
                    }
                    else
                    {
                        return RedirectToAction("AddTeacher");
                    }
                }
            }

            return View(teacher);
        }
        #endregion

        #region UpdateTeacher
        /// <summary>
        /// Pre update a teacher
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>View</returns>
        public ActionResult UpdateTeacher(int id)
        {
            if (Request.IsAjaxRequest())
            {
                var gender = new List<SelectListItem>();
                gender.Add(new SelectListItem() { Text = "Nam", Value = "M" });
                gender.Add(new SelectListItem() { Text = "Nữ", Value = "F" });
                ViewBag.Genders = gender;
                Teacher _teacher = _teacherServices.GetTeacher(id);

                return View("UpdateTeacher", _teacher);
            }
            else

                return View();
        }

        /// <summary>
        /// Update a teacher
        /// </summary>
        /// <param name="teacher">Teacher</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult UpdateTeacher(Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                _teacherServices.UpdateTeacher(teacher);
                TempData["Msg"] = "Đã sửa thông tin giáo viên thành công";
                return RedirectToAction("Table");
            }

            return View(teacher);
        }
        #endregion

        #region DeleteTeacher
        /// <summary>
        /// Delete a teacher
        /// </summary>
        /// <param name="ID">ID</param>
        /// <returns>View</returns>
        public ActionResult DeleteTeacher(int ID)
        {
            if (ModelState.IsValid)
            {
                _teacherServices.DeleteTeacher(ID);
                TempData["Msg"] = "Đã xóa giáo viên thành công";
                return RedirectToAction("Table");
            }

            return View("Table");
        }
        #endregion

        #region AssignTeacher
        /// <summary>
        /// Pre assign a teacher
        /// </summary>
        /// <returns>View</returns>
        public ActionResult AssignTeacher()
        {
            if (ModelState.IsValid)
            {
                var teacherName = _teacherServices.GetAllTeacher().Select(t => new SelectListItem()
                {
                    Text = t.teacherName,
                    Value = t.teacherID.ToString(),
                }).ToList();

                var className = _teacherServices.GetAllClassInSchoolYears().Select(t => new SelectListItem()
                {
                    Text = t.className,
                    Value = t.classID.ToString(),
                }).ToList();

                var subjectName = _teacherServices.GetAllSubject().Select(t => new SelectListItem()
                {
                    Text = t.subjectName,
                    Value = t.subjectID.ToString(),
                }).ToList();

                var schoolYearName = _teacherServices.GetAllSchoolYear().Select(t => new SelectListItem()
                {
                    Text = t.schoolYearName,
                    Value = t.schoolYearID.ToString(),
                }).ToList();

                var model = new TeacherAndClassModels { TeacherSelectList = teacherName, ClassSelectList = className, SubjectSelectList = subjectName , SchoolYearSelectList = schoolYearName};

                return View(model);
            }
            else

                return View();
        }

        /// <summary>
        /// assign a teacher
        /// </summary>
        /// <param name="teacher">TeacherAndClassModels</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult AssignTeacher(TeacherAndClassModels teacher)
        {
            if (ModelState.IsValid)
            {
                TeachingAssignment teachingAssignment = new TeachingAssignment();
                teachingAssignment.teacherID = teacher._teacherID;
                teachingAssignment.classID = teacher._classID;
                teachingAssignment.subjectID = (byte)teacher._subjectID;
                teachingAssignment.schoolYearID = teacher._schoolYearID;
                _teacherServices.AssignTeacher(teachingAssignment);
                TempData["Msg"] = "Đã phân bổ giáo viên thành công";
                return RedirectToAction("Table");
            }

            return View(teacher);
        }
        #endregion

        #region ImportTeacher
        /// <summary>
        /// Pre import a list of teacher
        /// </summary>
        /// <returns>view</returns>
        public ActionResult ImportTeacher()
        {
            return View();
        }

        /// <summary>
        /// import a list of teacher
        /// </summary>
        /// <param name="fc">FormCollection</param>
        /// <param name="uploadFile">HttpPostedFileBase</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult ImportTeacher(FormCollection fc, HttpPostedFileBase uploadFile)
        {
            try
            {
                if (uploadFile.ContentLength > 0)
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"),
                    Path.GetFileName(uploadFile.FileName));
                    uploadFile.SaveAs(filePath);

                    var excel = new ExcelQueryFactory();
                    excel.FileName = filePath;
                    excel.AddMapping<Teacher>(x => x.teacherName, "Tên Giáo Viên");
                    excel.AddMapping<Teacher>(x => x.gender, "Giới tính");
                    excel.AddMapping<Teacher>(x => x.mobile, "SDT");
                    excel.AddMapping<Teacher>(x => x.address, "Địa chỉ");
                    excel.AddMapping<Teacher>(x => x.dateOfBirth, "Ngày Sinh");
                    var details = from x in excel.Worksheet<Teacher>("Sheet1")
                                  select x;
                    foreach (var detail in details)
                    {
                        Teacher teacher = new Teacher();
                        teacher.teacherName = detail.teacherName;
                        teacher.gender = detail.gender;
                        teacher.mobile = detail.mobile;
                        teacher.address = detail.address;
                        teacher.dateOfBirth = detail.dateOfBirth;
                        teacher.deactived = false;

                        _teacherServices.AddTeacher(teacher);
                    }
                }
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
            return RedirectToAction("Table");
        }
        #endregion
    }
}
